package com.zzh.takeoutapp.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.adapter.AddressAdapter;
import com.zzh.takeoutapp.adapter.EvaluateItemAdapter;
import com.zzh.takeoutapp.base.BaseActivity;
import com.zzh.takeoutapp.entity.OrderListBean;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.model.AddressBean;
import com.zzh.takeoutapp.model.PhotoInfo;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.service.ServiceUrl;
import com.zzh.takeoutapp.utils.GsonResolve;
import com.zzh.takeoutapp.utils.ImageManager;
import com.zzh.takeoutapp.utils.LoadingUtil;
import com.zzh.takeoutapp.utils.ToolBarHelper;
import com.zzh.takeoutapp.utils.UtilTool;
import com.zzh.takeoutapp.view.MultiImageView;

import net.arvin.pictureselector.entities.ImageEntity;
import net.arvin.pictureselector.utils.PSConfigUtil;
import net.arvin.pictureselector.utils.PSConstanceUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/30.
 */

public class EvaluateActivity extends BaseActivity implements MultiImageView.OnItemClickListener {

    @Bind(R.id.rb)
    RatingBar rb;//商家评分
    @Bind(R.id.rb_shop)
    RatingBar rb_shop;//配送评分
    @Bind(R.id.et_search)
    AppCompatEditText et_search;
    @Bind(R.id.iv_face)
    TextView iv_face;//时间
    @Bind(R.id.tv_shop_title)
    TextView tv_shop_title;
    @Bind(R.id.iv_shop_head)
    ImageView iv_shop_head;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.toolbar)
    Toolbar tbToolbar;
    @Bind(R.id.tv_submit)
    TextView tv_submit;
    @Bind(R.id.iv_refund_camera)
    MultiImageView multiImagView;
    @Bind(R.id.tv_refund_camera)
    LinearLayout tv_refund_camera;
    private List<PhotoInfo> photos;
    private final int REQUEST_CODE_1 = 1001;
    private ArrayList<ImageEntity> mItems;//用于显示的图集
    private EvaluateItemAdapter evaluateItemAdapter;
    private OrderListBean orderListBean;
    private final String EVALUATE_ACTIVITY = "EvaluateActivity";
    private LoadingUtil loadingUtil;
    private List<File> strings;

    @Override
    public void setContent() {
        setContentView(R.layout.activity_evaluate);
        ButterKnife.bind(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        initPhoto();
        orderListBean = (OrderListBean) getIntent().getSerializableExtra("orderListBean");
    }

    private void initPhoto() {
        mItems = new ArrayList<>();
        photos = new ArrayList<>();
        strings = new ArrayList<>();
        loadingUtil = new LoadingUtil(this);
        PSConfigUtil.getInstance()
                .setCanCrop(true)
                .setCanTakePhoto(true)
                .setMaxCount(1)
                .setStatusBarColor(R.color.blue);
        PhotoInfo phote = new PhotoInfo();
        phote.url = "" + ImageManager.resourceIdToUri(this, R.mipmap.indent_refund_camera);
        phote.w = 1280;
        phote.h = 720;
        photos.add(phote);
        multiImagView.setList(photos);
    }

    @Override
    public void initComponent() {
        ToolBarHelper.setTitleAndBackAndText(this, tbToolbar, "评价");
    }

    @Override
    public void setListener() {
        multiImagView.setOnItemClickListener(this);
        multiImagView.setOnItemClickListenerDelete(new MultiImageView.OnItemClickListenerDelete() {
            @Override
            public void onItemClick(View view, final int position) {
                //删除图片
                final PhotoInfo phote = photos.get(position);
                new AlertDialog.Builder(EvaluateActivity.this).
                        setMessage("你确定删除图片吗？")
                        .setNegativeButton("否", null)
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                multiImagView.removeListPhoto(position);
                                if (multiImagView.getImagesList().size() > 1) {
                                    tv_refund_camera.setVisibility(View.GONE);
                                } else {
                                    tv_refund_camera.setVisibility(View.VISIBLE);
                                }
                            }
                        })
                        .show();
            }
        });
    }

    @Override
    public void onAfterInit() {
        if (orderListBean != null) {
            ImageManager.loadUrlImage(this, orderListBean.getShop_logo(), iv_shop_head);
            tv_shop_title.setText(orderListBean.getShop_title());
            iv_face.setText(orderListBean.getCui_time());
            List<OrderListBean.ProductsBean> products = orderListBean.getProducts();
            evaluateItemAdapter = new EvaluateItemAdapter(products);
            recyclerView.setAdapter(evaluateItemAdapter);
            evaluateItemAdapter.notifyDataSetChanged();
        }

    }

    @OnClick({R.id.tv_submit})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_submit:
                Gson gson2 = new GsonBuilder().enableComplexMapKeySerialization().create();
                if (orderListBean != null) {
                    loadingUtil.startShowLoading();
                    ServiceUrl.CommentService(this, rb.getRating()
                            , et_search.getText().toString()
                            , rb_shop.getRating()
                            , orderListBean.getOrder_id()
                            , orderListBean.getPei_time()
                            , gson2.toJson(evaluateItemAdapter.map)
                            , strings
                            , EVALUATE_ACTIVITY);
                }
                break;
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        if (position == 0) {
            if (multiImagView.getImagesList().size() >= 10) {
                UtilTool.toast(EvaluateActivity.this, "最多上传九张图片");
            } else {
                openPs();
            }
        } else {
            ImagePagerActivity.ImageSize imageSize =
                    new ImagePagerActivity.ImageSize(view.getMeasuredWidth(), view.getMeasuredHeight());
            List<String> photoUrls = new ArrayList<>();
            for (int i = 1; i < photos.size(); i++) {//第一张不是图片
                PhotoInfo photoInfo = photos.get(i);
                photoUrls.add(photoInfo.url);
            }
            ImagePagerActivity.startImagePagerActivity(EvaluateActivity.this, photoUrls, position - 1, imageSize);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_1: {
                    getHeadPortrait(data);
                    break;
                }
            }
        }
    }

    private void getHeadPortrait(Intent data) {
        mItems.clear();
        List<ImageEntity> temp = data.getParcelableArrayListExtra(PSConstanceUtil.PASS_SELECTED);
        mItems.addAll(temp);
        for (ImageEntity entity : temp) {
            strings.add(new File(entity.getPath()));
        }
        for (ImageEntity entity : temp) {
            PhotoInfo phote = new PhotoInfo();
            phote.url = entity.getPath();
            phote.w = 1280;
            phote.h = 720;
            photos.add(phote);
        }
        multiImagView.setList(photos);
        if (multiImagView.getImagesList().size() > 1) {
            tv_refund_camera.setVisibility(View.GONE);
        } else {
            tv_refund_camera.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void backFromSetting() {
        super.backFromSetting();
        openPs();
    }

    private void openPs() {
        String perms[] = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        checkPermission(new CheckPermListener() {
            @Override
            public void agreeAllPermission() {
                PSConfigUtil.getInstance().showSelector(EvaluateActivity.this, REQUEST_CODE_1, mItems);
            }
        }, "获取相片需要使用相机和内存读写权限", perms);
    }

    @Override
    public void onItemLongClick(View view, int position) {

    }

    @Override
    public void onStart() {
        super.onStart();
        EventbusHelper.register(this);
    }

    @Override
    public void onStop() {
        loadingUtil.stopShowLoading();
        EventbusHelper.unregister(this);
        super.onStop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(NetMsgEvent event) {
        String _msgType = (String) event.getMsgType();
        JSONObject jsonObject = event.getMsgJSONObj();
        switch (_msgType) {
            case EVALUATE_ACTIVITY:
                loadingUtil.stopShowLoading();
                if (jsonObject != null)
                    if (jsonObject.optString("error").equals("0")) {
                        UtilTool.toast(this, jsonObject.optString("message"));
                    }
                break;
        }
    }


}
